package com.xingfei.blog.controller;

import com.xingfei.blog.common.JsonResult;
import com.xingfei.blog.constants.ErrorConstants;
import com.xingfei.blog.controller.base.BaseController;
import com.xingfei.blog.service.WebAttentionService;
import com.xingfei.blog.utils.UserThreadLocal;
import com.xingfei.blog.vo.UserAttentionVo;
import com.xingfei.blog.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * 关注相关接口
 *
 * @author: chenxingfei
 * @time: 2017/4/3  21:22
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/attention")
public class AttentionController extends BaseController {

    public static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
    @Autowired
    private WebAttentionService webAttentionService;

    /**
     * 添加关注和取消关注
     *
     * @param userAttentionVo
     * @return
     */
    @PostMapping("/addOrCancelAttention")
    @ResponseBody
    public JsonResult attention(HttpServletRequest request, UserAttentionVo userAttentionVo) {
        String errorCode = ErrorConstants.LOGIN_ERROR;
        String errorMessage = "添加失败";
        if (userAttentionVo == null) {
            errorCode = ErrorConstants.RES_SERVICE_STRING;
            errorMessage = "参数错误";
        }
        //校验用户是否登陆，没有登录则跳转至登录页面
        UserVO userVO = UserThreadLocal.get();
        if (userVO == null) {
            errorCode = ErrorConstants.LOGIN_ERROR;
            errorMessage = "用户未登录";
        }else{
            try {
                boolean result = webAttentionService.addOrDeleteAttention(userAttentionVo);
                if (result) {
                    errorCode = ErrorConstants.SERVER_SUCCESS;
                    errorMessage = "操作成功";
                }
            } catch (Exception e) {
                logger.error("关注或取消关注异常，e={}", e.toString());
                e.printStackTrace();
                errorCode = ErrorConstants.SERVER_ERROR;
                errorMessage = "服务错误";
            }
        }
        JsonResult jsonResult = new JsonResult(errorCode, errorMessage);
        return jsonResult;
    }
}
